import axios from 'axios';
import { Base64 } from 'js-base64';
import config from '../../config';



export default function (req) {
  const instance = axios.create({
    baseURL: __SERVER__ ? config.proxyUrl : '/api',
    transformRequest: [
      // data => Object.entries(data)
      // .map(item => `${encodeURIComponent(item[0])}=${encodeURIComponent(item[1])}`)
      // .join('&')
      data => {
        return data ? Object.entries(data)
        .map(item => `${encodeURIComponent(item[0])}=${encodeURIComponent(item[1])}`)
        .join('&') : ''
      }
      // __CLIENT__ && `${encodeURIComponent('access_token')}=${encodeURIComponent(sessionStorage.getItem("token"))}`,
    ],
    headers:{
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${Base64.encode('crm-wx:tianwu_crm')}`,
    }
  });

  let token;

  instance.setJwtToken = newToken => {
    token = newToken;
  };

  instance.interceptors.request.use(
    conf => {
      if (__SERVER__) {
        if (req.header('cookie')) {
          conf.headers.Cookie = req.header('cookie');
        }
        if (req.header('authorization')) {
          conf.headers.authorization = req.header('authorization');
        }
      }

      if (token) {
        conf.headers.authorization = token;
      }

      return conf;
    },
    error => Promise.reject(error)
  );

  instance.interceptors.response.use(
    response => {
      if(Number(response.data.status) === 1 && response.data.err === 'invalid_token'){ //登陆过期判断
        location.href = '/login?invalid_token=true';
      }
      return response.data
    },
    error => Promise.reject(error.response ? error.response.data : error)
  );

  return instance;
}